package com.cxb.manager;

import static android.content.Context.CONTEXT_IGNORE_SECURITY;
import static android.content.Context.CONTEXT_INCLUDE_CODE;
import static android.content.Context.MODE_PRIVATE;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.ActivityManager;
import android.app.ActivityManager.RunningTaskInfo;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.PowerManager;
import android.util.Log;
import android.widget.Toast;

import com.cxb.CXBApplication;
import com.cxb.MainActivity;
import com.cxb.R;
import com.cxb.entity.GpsDestinationInfo;
import com.cxb.utils.CommonUtils;
import com.cxb.utils.Config;
import com.cxb.utils.Debug;
import com.cxb.utils.SharedPreferencesUtils;
import com.cxb.utils.Tts;

/**
 * 
 * 描述：一键导航管理类 陈伟斌 2014-3-17
 */
public class NavigationManager {

	private Context mContext;

	private static boolean request_navigation_flag = false;
	private static int request_count = 0;
	private LocationManager locationManager;
	private SharedPreferencesUtils spUtils;
	private PhoneManager phoneManager;
	private Handler mHandler;
	private HistoryManager historyManager;
	private PowerManager powerManager;
	public static GpsDestinationInfo gpsDestinationInfoNeed2Navi;
	private Intent navIntent;
	private NaviTask cacheNaviTask;
	public NavigationManager(Context context) {
		this.mContext = context;
		locationManager = (LocationManager) context
				.getSystemService(Context.LOCATION_SERVICE);
		spUtils = new SharedPreferencesUtils(context);
		phoneManager = new PhoneManager(context);
		historyManager = new HistoryManager(mContext);
		powerManager = (PowerManager) context
				.getSystemService(Context.POWER_SERVICE);
		mHandler = new Handler();
	}

	/**
	 * 启动导航信息监听
	 * 
	 * 陈伟斌 2014-3-17
	 */
	public void startupNavigationListener() {
		CxbEventBus.getCxbBus(CxbEventBus.EVENT_RECEIVER_NAVIGATION).register(
				this);
		CxbEventBus.getCxbBus(CxbEventBus.EVENT_REQUEST_NAVATION)
				.register(this);
	}

	/**
	 * 取消监听
	 * 
	 * 陈伟斌 2014-3-17
	 */
	public void stopNavigationListener() {
		CxbEventBus.unResgist(CxbEventBus.EVENT_RECEIVER_NAVIGATION, this);
		CxbEventBus.unResgist(CxbEventBus.EVENT_REQUEST_NAVATION, this);
	}

	/**
	 * 收到导航(短信会走这条通道)
	 * 
	 * @param destination
	 *            陈伟斌 2014-3-17
	 */
	public void onEventBackgroundThread(GpsDestinationInfo destination) {

		if (destination == null || !request_navigation_flag) {
			return;
		}
		startupNavigation(destination);
		request_navigation_flag = false;
	}

	public void startupNavigation(final GpsDestinationInfo destination) {
		Debug.printfLog("startupNavigation " + destination + " bootTime="
				+ CXBApplication.bootTime);
		if ((System.currentTimeMillis() - CXBApplication.bootTime < 8000)
				|| !Environment.MEDIA_MOUNTED.equals(Environment
						.getExternalStorageState())) {// 等待挂机

			gpsDestinationInfoNeed2Navi = destination;
			mHandler.postDelayed(new Runnable() {

				@Override
				public void run() {
					startupNavigation(destination);

				}
			}, 1000);
			return;

		} else if (!powerManager.isScreenOn()) {
			CommonUtils.wakeUpScreen(mContext);
			mHandler.postDelayed(new Runnable() {

				@Override
				public void run() {
					startupNavigation(destination);

				}
			}, 2000);
			return;
		}

		if (destination != null) {

			if (Config.getMapDefault(mContext) == Config.MAP_BAIDU) {
				Uri uri = Uri
						.parse("bdnavi://plan?coordType=gcj02ll&src=com.cxb&dest="
								+ destination.latitude
								+ ","
								+ destination.longitude
								+ ","
								+ destination.destName);
				navIntent = new Intent("com.baidu.navi.action.START", uri);
				navIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			} else if (Config.getMapDefault(mContext) == Config.MAP_AUTOMAP) {
				Uri gaodeUri = Uri
						.parse("androidamap://navi?sourceApplication="
								+ "com.cxb" + "&poiname="
								+ destination.destName + "&lat="
								+ destination.latitude + "&lon="
								+ destination.longitude + "&dev=0&style=2");
				navIntent = new Intent("android.intent.action.VIEW", gaodeUri);
				navIntent.setPackage("com.autonavi.minimap");
				navIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			} else if (Config.getMapDefault(mContext) == Config.MAP_AUTONAVI) {
				navIntent = new Intent("com.autonavi.xmgd.action.NAVIGATOR");
				navIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				navIntent.setData(Uri.parse("NAVI:" + destination.longitude
						+ "," + destination.latitude + ","
						+ destination.destName));
			} else if (Config.getMapDefault(mContext) == Config.MAP_AUTOMAP_CAR) {
				navIntent=new Intent();
				navIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
						| Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
				navIntent.addCategory("android.intent.category.DEFAULT");
				navIntent.setData(Uri
						.parse("androidauto://navi?sourceApplication=amap&lat="
								+ destination.latitude + "&lon="
								+ destination.longitude + "&dev=1&style=2"));
				navIntent.setPackage("com.autonavi.amapauto");

			}else if (Config.getMapDefault(mContext) == Config.MAP_AUTOMAP_LITE) {
				navIntent=new Intent();
				navIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
						| Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
				navIntent.addCategory("android.intent.category.DEFAULT");
				navIntent.setData(Uri
						.parse("androidauto://navi?sourceApplication=amap&lat="
								+ destination.latitude + "&lon="
								+ destination.longitude + "&dev=1&style=2"));
				navIntent.setPackage("com.autonavi.amapautolite");

			}
			Debug.printf(
					"test",
					"receiver data="
							+ ("NAVI:" + destination.latitude + "," + destination.longitude));

			if (MainActivity.tts != null) {
				mHandler.post(new Runnable() {

					@Override
					public void run() {
						if (destination.destName != null
								&& !destination.destName.equals("")) {
							if (destination.isQunMsg) {

								Toast.makeText(
										mContext,
										mContext.getString(
												R.string.start_qun_navigation,
												destination.destName), Toast.LENGTH_SHORT)
										.show();
								Tts.speak(mContext.getString(
										R.string.start_qun_navigation,
										destination.destName));
							} else {
								Toast.makeText(
										mContext,
										mContext.getString(R.string.navi_tip,
												destination.destName), Toast.LENGTH_SHORT)
										.show();
								Tts.speak(mContext.getString(R.string.navi_tip,
										destination.destName));
							}
						}

					}

				});
			}
			mHandler.postDelayed(new Runnable() {

				@Override
				public void run() {

					// TODO Auto-generated method stub

					if (CommonUtils.isUSBMass()) {
						Toast.makeText(mContext,
								R.string.usb_mass_cannot_use_map_navi, Toast.LENGTH_SHORT)
								.show();
						Tts.speak(mContext
								.getString(R.string.usb_mass_cannot_use_map_navi));
						return;
					}

					mContext.startActivity(navIntent);
					historyManager.addHistory(destination);

				}
			}, 3000);
			if (!powerManager.isScreenOn()) {
				// 唤醒屏幕
				RootContext.getInstance().runCommand("input keyevent 85");
			}
			mContext.sendBroadcast(new Intent("preview_window_off"));
			// /////////////////////////////////////////////////////////////////////
		}
	}

	double x_pi = 3.14159265358979324 * 3000.0 / 180.0;

	public Map<String, Double> BDMapRncrypt(double gg_lat, double gg_lon) {
		double bd_lat;
		double bd_lon;
		double x = gg_lon, y = gg_lat;
		double z = Math.sqrt(x * x + y * y) + 0.00002 * Math.sin(y * x_pi);
		double theta = Math.atan2(y, x) + 0.000003 * Math.cos(x * x_pi);
		Map<String, Double> map = new HashMap<String, Double>();
		bd_lon = z * Math.cos(theta) + 0.0065;
		bd_lat = z * Math.sin(theta) + 0.006;
		map.put("bd_lat", bd_lat);
		map.put("bd_lng", bd_lon);
		return map;
	}

	/**
	 * 请求导航开始(网络通道 )
	 * 
	 * @param obj
	 *            陈伟斌 2014-3-17
	 */
	public void onEventBackgroundThread(Object obj) {
		// // 1.开始下载
		// request_navigation_flag = true;
		// // 增加循环
		// while (request_navigation_flag) {
		// request_count++;
		// if (downloadNaviInfo()) {// 成功下载gps 信息
		// request_navigation_flag = false;
		// break;
		// } else {
		// try {
		// if (request_count > 60) {// 最多只尝试请求60次
		// request_count = 0;
		// break;
		// }
		// Thread.sleep(3000);// 每隔3秒重复请求一次
		//
		// } catch (InterruptedException e) {
		//
		// e.printStackTrace();
		// }
		// }
		// }

	}

	public boolean isBaiduNaviRunning() {
		ActivityManager activityManager = (ActivityManager) mContext
				.getSystemService(Context.ACTIVITY_SERVICE);
		List<RunningTaskInfo> tasks = activityManager.getRunningTasks(10);

		for (RunningTaskInfo task : tasks) {
			if (task.baseActivity.getPackageName().equals("com.baidu.navi")) {
				return true;
			}
		}
		return false;
	}



	public void dealNaviDelay(GpsDestinationInfo gpsDestinationInfo) {
		dealNaviDelay(gpsDestinationInfo, 1000);
	}

	private void dealNaviDelay(GpsDestinationInfo gpsDestinationInfo, long delayTime) {
		Debug.printfLog("dealNavi " + gpsDestinationInfo);
		if (gpsDestinationInfo != null) {
			// naviCacheList.add(gpsDestinationInfo);
			addCacheNavigation(mContext, gpsDestinationInfo);

			if (cacheNaviTask == null) {
				cacheNaviTask = new NaviTask();
				mHandler.postDelayed(cacheNaviTask, delayTime);

			}
		}
	}

	class NaviTask implements Runnable {
		@Override
		public void run() {
			if (!PowerOffState.isPowerOffing) {

				GpsDestinationInfo lastDestination = getLastNavigation(mContext);
				if (lastDestination != null) {

					startupNavigation(lastDestination);
					cacheNaviTask = null;
					clearCacheNavigation(mContext);

				}
			} else {
				// 正在关机，延时执行，直于关机事件取消
				mHandler.postDelayed(this, 2000);
			}
		}
	}

	public void addCacheNavigation(Context context, GpsDestinationInfo naviInfo) {
		Debug.printfLog("addCacheNavigation naviInfo=" + naviInfo);
		List<GpsDestinationInfo> list = getCacheNavigation(context);
		if (list == null) {
			list = new ArrayList<GpsDestinationInfo>();
		}
		list.add(naviInfo);

		try {
			File file = new File(context.getCacheDir(), "cache_navigation");
			if (!file.exists()) {
				file.createNewFile();
			}
			ObjectOutputStream oos = new ObjectOutputStream(
					new FileOutputStream(file));

			oos.writeObject(list);
			oos.flush();
			oos.close();
		} catch (Exception e) {
			Debug.printfLog(e);
			e.printStackTrace();
		}
	}

	public GpsDestinationInfo getLastNavigation(Context context) {
		List<GpsDestinationInfo> list = getCacheNavigation(context);

		Debug.printfLog("getLastNavigation list=" + list);
		if (list != null && list.size() > 0) {
			Debug.printfLog("getLastNavigation list=" + list.size());
			GpsDestinationInfo result = list.get(list.size() - 1);
			Debug.printfLog("result " + result + "  index=" + (list.size() - 1));
			return result;
		}
		return null;

	}

	public List<GpsDestinationInfo> getCacheNavigation(Context context) {
		File file = new File(context.getCacheDir(), "cache_navigation");
		if (!file.exists()) {
			return null;
		}
		List<GpsDestinationInfo> list = null;
		try {
			ObjectInputStream ois = new ObjectInputStream(new FileInputStream(
					file));
			list = (List<GpsDestinationInfo>) ois.readObject();
			ois.close();
		} catch (Exception e) {
			Debug.printfLog(e);
			e.printStackTrace();
		}
		Debug.printfLog("getCacheNavigation list=" + list);
		return list;
	}

	public void clearCacheNavigation(Context context) {
		File file = new File(context.getCacheDir(), "cache_navigation");
		if (file.exists()) {
			file.delete();
		}
	}

	public static class DefaultConfig{
		//这五个参数用来配置高德地图默认参数，如果这样配置的话，可以去掉第一
		//次启动高德导航时的欢迎界面，同时开启：保持屏幕常亮，实时播报路况这两项功能
		public static final String DEFAULT_VERNAME = "7.6.0.2058";
		public static final int DEFAULT_VERSION_CODE = 560;
		public static final boolean DEFAULT_ISSPLASHNEEDSHOW = true;
		public static final boolean DEFAULT_MAPROADSTATUS = true;
		public static final boolean DEFAULT_SCREENON = true;

		public static final String GAO_DE_PACKAGE = "com.autonavi.minimap";
		public static final String DIR_PATH = "/data/data/"+GAO_DE_PACKAGE+"/shared_prefs";
		public static final String FILE_PATH = "/data/data/"+GAO_DE_PACKAGE+"/shared_prefs/SharedPreferences.xml";

		private int uid;
		private int gid;
		private int versionCode;
		private String versionName;
		private Context mContext;
		private String mSrcPath;
		public DefaultConfig(Context context){
			mContext = context;
			PackageManager pm = context.getPackageManager();
			ApplicationInfo ai = null;
			PackageInfo packageInfo = null;
			try {
				ai = pm.getApplicationInfo(
						GAO_DE_PACKAGE,
						PackageManager.GET_ACTIVITIES);
				uid = ai.uid;
				gid = ai.uid;

				packageInfo = pm.getPackageInfo(GAO_DE_PACKAGE, 0);
				versionCode = packageInfo.versionCode;
				versionName = packageInfo.versionName;

			} catch (PackageManager.NameNotFoundException e) {
				e.printStackTrace();
			}

			mSrcPath = "/data/data/"+mContext.getPackageName()+"/shared_prefs/navisetings.xml";
		}


		public  void setNaviDefaultConfig(){
			if(!isDirExist()){
				createDir();
				copyFile();
				return;
			}else {
				Log.d("debug", "errors????");
			}
		}

		/**
		 * 给高德地图创建 sharedpreference 目录, 同时创建SharedPreferences.xml
		 */
		private void createDir(){
			// 创建目录 /data/data/com.autonavi.minimap/shared_prefs，同时修改用户及组，和文件权限
			File dir = new File(DIR_PATH);
			RootContext.runCommandForResult("mkdir -p " + dir.getAbsolutePath());
			RootContext.runCommandForResult("chmod 771 " + dir.getAbsolutePath());
			RootContext
					.runCommandForResult("chown "
							+ uid
							+ ":"
							+ gid
							+ " " + dir.getAbsolutePath());

			//创建文件，并修改成777权限
			RootContext.runCommandForResult("touch " + FILE_PATH);
			RootContext.runCommandForResult("chmod 777 " + FILE_PATH);
			//LogUtil.print("copy file to navi  shared prefs ");

		}


		private void copyFile(){
			SharedPreferences sp = mContext.getSharedPreferences("navisetings", MODE_PRIVATE);
			SharedPreferences.Editor editor = sp.edit();
			editor.putString("versionName", versionName);
			editor.putInt("versionCode",versionCode);
			editor.putBoolean("isSplashNeedShow", DEFAULT_ISSPLASHNEEDSHOW);
			editor.putBoolean("MapRoadStatus", DEFAULT_MAPROADSTATUS);
			editor.putBoolean("screenon", DEFAULT_SCREENON);
			editor.commit();
			RootContext.runCommandForResult("cp -rf " + mSrcPath + " " + FILE_PATH);

			//修改权限，及组。必须修改
			RootContext.runCommandForResult("chmod 660 " + FILE_PATH);
			RootContext
					.runCommandForResult("chown "
							+ uid
							+ ":"
							+ gid
							+ " " + FILE_PATH);
		}


		private boolean isDirExist(){
			boolean isExist = false;
			File dir = new File(DIR_PATH);
			if(dir.exists()){
				isExist = true;
			}
			return isExist;
		}

		/**
		 * 创建高德地图上下文
		 * @param context 非高德地图的上下文
		 * @return 高德地图上下文
		 */
		public static Context createGaoDeMapContext(Context context){
			try {
				Context mapContext = context.createPackageContext(GAO_DE_PACKAGE, CONTEXT_IGNORE_SECURITY|CONTEXT_INCLUDE_CODE);
				return mapContext;
			} catch (PackageManager.NameNotFoundException e) {
				e.printStackTrace();
			}
			return null;
		}
	}
}
